package com.service;

import com.entity.MaintenanceAreaLevel1;
import com.repository.MaintenanceAreaLevel1Repository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Optional;

@Service
@Transactional
public class MaintenanceAreaLevel1Service {

    @Autowired
    private MaintenanceAreaLevel1Repository maintenanceAreaLevel1Repository;

    /**
     * 保存一级维护区域
     * @param maintenanceAreaLevel1 一级维护区域
     * @return 保存后的对象
     */
    public MaintenanceAreaLevel1 save(MaintenanceAreaLevel1 maintenanceAreaLevel1) {
        if (maintenanceAreaLevel1.getId() == null) {
            maintenanceAreaLevel1.setCreateTime(new Date());
        }
        maintenanceAreaLevel1.setUpdateTime(new Date());
        return maintenanceAreaLevel1Repository.save(maintenanceAreaLevel1);
    }

    public void deleteByAreaName(String areaName) {
        maintenanceAreaLevel1Repository.deleteAllByAreaName(areaName);
    }

    /**
     * 根据ID获取一级维护区域
     * @param id ID
     * @return 一级维护区域
     */
    @Transactional(readOnly = true)
    public Optional<MaintenanceAreaLevel1> findById(Integer id) {
        return maintenanceAreaLevel1Repository.findById(id);
    }

    /**
     * 分页查询一级维护区域
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 分页结果
     */
    @Transactional(readOnly = true)
    public Page<MaintenanceAreaLevel1> findAll(int pageNum, int pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.by(Sort.Direction.DESC, "createTime"));
        return maintenanceAreaLevel1Repository.findAll(pageable);
    }

    /**
     * 根据区域名称模糊查询一级维护区域
     * @param areaName 区域名称
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 分页结果
     */
    @Transactional(readOnly = true)
    public Page<MaintenanceAreaLevel1> findByAreaNameContaining(String areaName, int pageNum, int pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.by(Sort.Direction.DESC, "createTime"));
        return maintenanceAreaLevel1Repository.findByAreaNameContaining(areaName, pageable);
    }
}